package com.ruoyi.back.service.impl

import cn.hutool.json.JSONUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.ruoyi.back.domain.ChannelFunction
import com.ruoyi.back.domain.FunctionInfo
import com.ruoyi.back.mapper.ChannelFunctionMapper
import com.ruoyi.back.service.ChannelFunctionService
import com.ruoyi.back.service.FunctionService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class ChannelFunctionServiceImpl : ServiceImpl<ChannelFunctionMapper, ChannelFunction>(), ChannelFunctionService {

    @Autowired
    private lateinit var functionService: FunctionService

    override fun getFunctionStrByChannel(channelId: Long): String =
        getFunctionByChannel(channelId)
            .takeIf { it.isNotEmpty() }
            ?.run {
                mapNotNull { functionService.getFunctionNameById(it.functionId!!) }
                    .joinToString(",")
            }
            ?: "-"

    override fun getFunctionInfoByChannel(channelId: Long): List<FunctionInfo>? =
        getFunctionByChannel(channelId)
            .takeIf { it.isNotEmpty() }
            ?.run {
                map {
                    FunctionInfo().apply {
                        functionId = it.functionId
                        delay = it.delay
                        functionName = functionService.getFunctionNameById(it.functionId!!)
                    }
                }
            }
    override fun getFunctionByChannel(channelId: Long): List<ChannelFunction> =
        list(
            KtQueryWrapper(ChannelFunction::class.java)
                .eq(ChannelFunction::channelId, channelId)
        )

    override fun getFunctionIdsByChannel(channelId: Long): String? =
        getFunctionByChannel(channelId)
            .takeIf { it.isNotEmpty() }
            ?.run { joinToString { it.functionId.toString() } }

    override fun updateChannelFunctions(functionIds: String?, channelId: Long): Boolean {

        var functionInfos: List<FunctionInfo>? = null
        try {
            functionInfos = functionIds?.run { JSONUtil.toList(functionIds, FunctionInfo::class.java) }
        }catch (_: Exception) {}

        return functionInfos?.run {
            remove(
                KtUpdateWrapper(ChannelFunction::class.java)
                    .eq(ChannelFunction::channelId, channelId)
            )

            return saveBatch(map {
                ChannelFunction().apply {
                    this.channelId = channelId
                    functionId = it.functionId
                    delay = it.delay
                }
            })
        } ?: true
    }

}